/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.CommonUtil;
import com.star.common.RenderModel;
import com.star.common.UserRole;
import com.star.common.ActionData;
import com.star.common.ActionType;
import com.star.common.UserData;
import com.start.model.ActionModel;
import com.start.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class AdminActionController extends HttpServlet{
    private static final Logger logger = Logger.getLogger(AdminCateController.class);
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    private static final int ACTION_PER_PAGE = 10;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }
    
    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminActionController.handle:" + ex.getMessage(), ex);
        }
    }
    
    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/search":
                content = renderEditPage(req, resp);
                break;            
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.ACTION_VIEW)) {
                resp.sendRedirect("/");
                return "";
            }
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, ""));
            dic.setVariable("PAGE_TITLE", "Xem log");       
                       
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
                        
            ActionModel actionModel = ActionModel.getInstance();            
            List<ActionData> lstAction = actionModel.getAction((page - 1) * ACTION_PER_PAGE, ACTION_PER_PAGE);
            if (lstAction != null && !lstAction.isEmpty()) {
                for (ActionData actionData : lstAction) {
                    TemplateDataDictionary section = dic.addSection("LIST_ACTION");
                    section.setVariable("USER_NAME", String.valueOf(actionData.getUser()));
                    ActionType actionType = ActionType.getById(actionData.getAction());
                    section.setVariable("ACTION_NAME", actionType.getAction());
                    section.setVariable("ACTION_DETAIL", actionData.getValue());
                    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
                    Date d = new Date(actionData.getCreated());            
                    section.setVariable("TIME", sdf.format(d));
                    boolean test = true;
                    List<ActionData> lstActionSub = actionModel.getActionByPid(0, -1, actionData.getPid());
                    switch(actionData.getAction()){
                        case 1:
                        case 2:
                            for(ActionData item : lstActionSub){
                                if(item.getAction() == 3){
                                    section.showSection("HIDE_LINK");
                                    test = false;
                                    break;
                                }                                    
                            }
                            if(test == true){
                                section.showSection("SHOW_LINK");
                                section.setVariable("LINK_ACTION", "/profile/edit?id=" + actionData.getPid());
                            }                            
                            break;
                        case 4:
                        case 5:
                            for(ActionData item : lstActionSub){
                                if(item.getAction() == 6){
                                    section.showSection("HIDE_LINK");
                                    test = false;
                                    break;
                                }                                    
                            }
                            if(test == true){
                                section.showSection("SHOW_LINK");
                                section.setVariable("LINK_ACTION", "/post/edit?id=" + actionData.getPid());
                            }                            
                            break;
                        case 7:
                        case 8:
                            for(ActionData item : lstActionSub){
                                if(item.getAction() == 9){
                                    section.showSection("HIDE_LINK");
                                    test = false;
                                    break;
                                }                                    
                            }
                            if(test == true){
                                section.showSection("SHOW_LINK");
                                section.setVariable("LINK_ACTION", "/cate");
                            }                            
                            break;
                        case 10:
                        case 11:
                        case 13:
                            for(ActionData item : lstActionSub){
                                if(item.getAction() == 12){
                                    section.showSection("HIDE_LINK");
                                    test = false;
                                    break;
                                }                                    
                            }
                            if(test == true){
                                section.showSection("SHOW_LINK");
                                section.setVariable("LINK_ACTION", "/user/edit?id=" + actionData.getPid());
                            }                            
                            break;                            
                        case 14:
                        case 15:
                            for(ActionData item : lstActionSub){
                                if(item.getAction() == 16){
                                    section.showSection("HIDE_LINK");
                                    test = false;
                                    break;
                                }                                    
                            }
                            if(test == true){
                                section.showSection("SHOW_LINK");
                                section.setVariable("LINK_ACTION", "/newscate");
                            }
                            break;
//                        case 17:
//                        case 18:
                        case 20:    
                            for(ActionData item : lstActionSub){
                                if(item.getAction() == 19){
                                    section.showSection("HIDE_LINK");
                                    test = false;
                                    break;
                                }                                    
                            }
                            if(test == true){
                                section.showSection("SHOW_LINK");
                                section.setVariable("LINK_ACTION", "/post/edit?id=" + actionData.getPid());
                            }
                            break;
                        case 22:
                        case 23:
                            for(ActionData item : lstActionSub){
                                if(item.getAction() == 24){
                                    section.showSection("HIDE_LINK");
                                    test = false;
                                    break;
                                }                                    
                            }
                            if(test == true){
                                section.showSection("SHOW_LINK");
                                section.setVariable("LINK_ACTION", "/usergroup/edit?id=" + actionData.getPid());
                            }                            
                            break;   
                        default: 
                            section.showSection("HIDE_LINK");                            
                    }                                        
                }
            }
            
            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("USER_LIST");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername());                
            }

            int count = (int) actionModel.getActionCount();
            String pageNavi = CommonUtil.getPageNavi(page, count, ACTION_PER_PAGE, "");
            dic.setVariable("PAGENAVI", pageNavi);
            
            Template template = RenderModel.getAdminCTemplate("action_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminActionController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    
    private String renderEditPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.ACTION_VIEW)) {
                return CommonUtil.toPermissionDenied();
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, ""));
            dic.setVariable("PAGE_TITLE", "Xem log");       
               
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
            //int count = 0;
            
            String user = req.getParameter("postUser") != null ? req.getParameter("postUser") : "";
            String dateFrom = req.getParameter("tuNgay") != null ? req.getParameter("tuNgay") : "";
            String dateTo = req.getParameter("denNgay") != null ? req.getParameter("denNgay") : "";
            String nameDetail = req.getParameter("detail") != null ? req.getParameter("detail") : "";
            String userSearch = "";
            if(!user.equals("")){
                UserModel userModelSearch = UserModel.getInstance();
                UserData userDataSearch = userModelSearch.getUserById(user);
                userSearch = userDataSearch.getUsername();
            }
                        
            ActionModel actionModel = ActionModel.getInstance();            
            List<ActionData> lstAction = actionModel.getAction(0, -1, userSearch, nameDetail, dateFrom, dateTo);
            if (lstAction != null && !lstAction.isEmpty()) {
                //for (ActionData actionData : lstAction) 
                for(int i = (page - 1) * ACTION_PER_PAGE; i < page * ACTION_PER_PAGE; i++){                    
                    //if(test == true){
                    //count += 1;
                    if(i == lstAction.size())
                        break;
                    ActionData actionData = lstAction.get(i);
                        TemplateDataDictionary section = dic.addSection("LIST_ACTION");
                        section.setVariable("USER_NAME", String.valueOf(actionData.getUser()));
                        ActionType actionType = ActionType.getById(actionData.getAction());
                        section.setVariable("ACTION_NAME", actionType.getAction());
                        section.setVariable("ACTION_DETAIL", actionData.getValue());
                        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
                        Date d = new Date(actionData.getCreated());            
                        section.setVariable("TIME", sdf.format(d));
                                                
                        boolean testsw = true;
                        List<ActionData> lstActionSub = actionModel.getActionByPid(0, -1, actionData.getPid());
                        switch(actionData.getAction()){
                            case 1:
                            case 2:
                                for(ActionData item : lstActionSub){
                                    if(item.getAction() == 3){
                                        section.showSection("HIDE_LINK");
                                        testsw = false;
                                        break;
                                    }                                    
                                }
                                if(testsw == true){
                                    section.showSection("SHOW_LINK");
                                    section.setVariable("LINK_ACTION", "/profile/edit?id=" + actionData.getPid());
                                }                            
                                break;
                            case 4:
                            case 5:
                                for(ActionData item : lstActionSub){
                                    if(item.getAction() == 6){
                                        section.showSection("HIDE_LINK");
                                        testsw = false;
                                        break;
                                    }                                    
                                }
                                if(testsw == true){
                                    section.showSection("SHOW_LINK");
                                    section.setVariable("LINK_ACTION", "/post/edit?id=" + actionData.getPid());
                                }                            
                                break;
                            case 7:
                            case 8:
                                for(ActionData item : lstActionSub){
                                    if(item.getAction() == 9){
                                        section.showSection("HIDE_LINK");
                                        testsw = false;
                                        break;
                                    }                                    
                                }
                                if(testsw == true){
                                    section.showSection("SHOW_LINK");
                                    section.setVariable("LINK_ACTION", "/cate");
                                }                            
                                break;
                            case 10:
                            case 11:
                            case 13:
                                for(ActionData item : lstActionSub){
                                    if(item.getAction() == 12){
                                        section.showSection("HIDE_LINK");
                                        testsw = false;
                                        break;
                                    }                                    
                                }
                                if(testsw == true){
                                    section.showSection("SHOW_LINK");
                                    section.setVariable("LINK_ACTION", "/user/edit?id=" + actionData.getPid());
                                }                            
                                break;                            
                            case 14:
                            case 15:
                                for(ActionData item : lstActionSub){
                                    if(item.getAction() == 16){
                                        section.showSection("HIDE_LINK");
                                        testsw = false;
                                        break;
                                    }                                    
                                }
                                if(testsw == true){
                                    section.showSection("SHOW_LINK");
                                    section.setVariable("LINK_ACTION", "/newscate");
                                }
                                break;
//                            case 17:
//                            case 18:
                            case 20:    
                                for(ActionData item : lstActionSub){
                                    if(item.getAction() == 19){
                                        section.showSection("HIDE_LINK");
                                        testsw = false;
                                        break;
                                    }                                    
                                }
                                if(testsw == true){
                                    section.showSection("SHOW_LINK");
                                    section.setVariable("LINK_ACTION", "/post/edit?id=" + actionData.getPid());
                                }
                                break;
                            case 22:
                            case 23:
                                for(ActionData item : lstActionSub){
                                    if(item.getAction() == 24){
                                        section.showSection("HIDE_LINK");
                                        testsw = false;
                                        break;
                                    }                                    
                                }
                                if(testsw == true){
                                    section.showSection("SHOW_LINK");
                                    section.setVariable("LINK_ACTION", "/usergroup/edit?id=" + actionData.getPid());
                                }                            
                                break;   
                            default: 
                                section.showSection("HIDE_LINK");                              
                        }                                                   
                   // }                    
                }
            }
            
            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("USER_LIST");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername());                
                if(user.equals(userData.getId()))
                    section.showSection("USER_SELECTED");
            }
            dic.setVariable("DATE_FROM", dateFrom);
            dic.setVariable("DATE_TO", dateTo);
            dic.setVariable("NAME_DETAIL", nameDetail);
                        
            int count = lstAction.size();
            String pageNavi = CommonUtil.getPageNavi(page, count, ACTION_PER_PAGE, "?" + req.getQueryString());
            dic.setVariable("PAGENAVI", pageNavi);

            Template template = RenderModel.getAdminCTemplate("action_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminActionController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
}
